package com.haizhi.beanstalk;

import com.dinstone.beanstalkc.*;
import com.dinstone.beanstalkc.internal.ConnectionInitializer;
import com.dinstone.beanstalkc.internal.DefaultBeanstalkClient;
import com.dinstone.beanstalkc.internal.operation.UseOperation;
import com.dinstone.beanstalkc.internal.operation.WatchOperation;

import java.util.Map;

/**
 * Created by youfeng on 2018/3/28.
 * beanstalk API 接口
 */
public class BeanstalkFactory {
    //获取到默认的jobs数目
    private static final String DEFAULT_JOBS_NUM = "888888";

    private final static int PRIORITY = 2147483647;


    //获得消费者
    public static BeanstalkClient getConsumer(String host, int port, String tube) {

        Configuration config = new Configuration();
        config.setServiceHost(host);
        config.setServicePort(port);

        ConnectionInitializer initializer = connection -> connection.handle(new WatchOperation(tube)).get();
        return new DefaultBeanstalkClient(config, initializer);
    }

    //获得生产者
    public static BeanstalkClient getProducer(String host, int port, String tube) {

        Configuration config = new Configuration();
        config.setServiceHost(host);
        config.setServicePort(port);

        ConnectionInitializer initializer = connection -> {
            if (tube != null) {
                connection.handle(new UseOperation(tube));
            }
        };
        return new DefaultBeanstalkClient(config, initializer);
    }

    //消费数据
    public static String reserve(JobConsumer consumer, int timeout) {
        Job job = consumer.reserveJob(timeout);
        if (job == null) {
            return null;
        }
        String result = new String(job.getData());
        consumer.deleteJob(job.getId());
        return result;
    }

    //生产数据
    public static long put(JobProducer producer, String data) {
        return producer.putJob(PRIORITY, 0, 10, data.getBytes());
    }

    //获得当前tube阻塞情况
    public static long getReadyJobsNum(BeanstalkClient beanstalkClient, String tube) {
        Map<String, String> result = beanstalkClient.statsTube(tube);
        return Integer.valueOf(result.getOrDefault("current-jobs-ready", DEFAULT_JOBS_NUM));
    }

}
